package medium.string;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode-cn.com/problems/words-frequency-lcci">面试题 16.02. 单词频率</a>
 * 设计一个方法，找出任意指定单词在一本书中的出现频率。
 * 你的实现应该支持如下操作：
 *      WordsFrequency(book)构造函数，参数为字符串数组构成的一本书
 *      get(word)查询指定单词在书中出现的频率
 * 示例：
 *      WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"});
 *      wordsFrequency.get("you"); //返回0，"you"没有出现过
 *      wordsFrequency.get("have"); //返回2，"have"出现2次
 *      wordsFrequency.get("an"); //返回1
 *      wordsFrequency.get("apple"); //返回1
 *      wordsFrequency.get("pen"); //返回1
 * @author 刘学松
 * @date 2021/2/12 20:27
 */
public class 单词频率 {
    private Map<String, Integer> map;

    public static void main(String[] args) {
        String[] array = {"i", "have", "an", "apple", "he", "have", "a", "pen"};
        单词频率 a = new 单词频率(array);
        System.out.println(a.get("have"));
    }

    public 单词频率(String[] book) {
        map = new HashMap<String, Integer>();
        for(String word : book) {
            map.merge(word, 1, Integer::sum);
        }
    }

    public int get(String word) {
        return this.map.getOrDefault(word, 0);
    }
}
